const getUserData = {
    taskConfig: { taskStatus: false },
    setting: {},
    data: {},
    saveFilePath: [],
    saveFileList: 0,
    watchValue(key, newVal) {
        if (key == 'taskStatus' && newVal) {
            if (getUserData.saveFilePath.length) {
                getUserData.saveFilePath.forEach((item) => {
                    files.remove(item)
                })
                getUserData.saveFilePath = []
            }
            Xhs.taskConfig.taskStatus = true
        }
        if (key == 'errorTask' && newVal) {
            let params = {
                taskType: getUserData.data.skey,
                task_id: getUserData.data.task_id,
                taskName: '私信回复指定用户',
                errorTip: newVal,
                taskData: getUserData.data,
                taskDate: Comman.getDate()
            }
            Xhs.errorTask(params)
            getUserData.taskConfig.taskStatus = true
        }
    },
    init(data) {
        getUserData.setting = data.setting || {}
        getUserData.data = data
        getUserData.saveFilePath = []
        getUserData.saveFileList = 0
        getUserData.taskConfig = Comman.defineReactive(
            {
                taskStatus: false,
                errorTask: '',
            },
            '',
            getUserData.watchValue
        )
        if (data.setting.image || data.setting.video) {
            getUserData.resolveMiddle({
                image: data.setting.image,
                video: data.setting.video
            })
        }
        getUserData.openTask()
    },
    start(data) {
        //初始化数据
        getUserData.init(data)
    },
    openTask() {
        let homeMnue = btnConfig.home.homeMnue
        let homeBtn = btnConfig.home.homeBtn
        let searchIconBtn = btnConfig.home.searchIconBtn
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        //点击首页
        let nowHomeBtn = homeBtn.default()
        if (!nowHomeBtn) {
            console.log('首页按钮不存在，请检查并手动复原首页重新启动');
            getUserData.taskConfig.errorTask = '首页按钮不存在'
            return
        }
        if (nowHomeBtn.bounds) {
            App.clickByBtn(nowHomeBtn, 3)
        } else {
            App.click(homeBtn.position.x, homeBtn.position.y, 3)
        }
        //点击搜索图标按钮
        let nowSearchIconBtn = searchIconBtn.default()
        if (!nowSearchIconBtn) {
            console.log('搜索图片不存在，并手动复原重新启动');
            getUserData.taskConfig.errorTask = '搜索图片不存在'
            return
        }
        if (nowSearchIconBtn.bounds) {
            App.clickByBtn(nowSearchIconBtn, 3)
        } else {
            App.click(searchIconBtn.position.x, searchIconBtn.position.y, 3)
        }
        if (!getUserData.setting.xhsid) {
            getUserData.taskConfig.errorTask = '任务参数并未配置xhsid参数'
            return
        }
        getUserData.searUser(getUserData.setting.xhsid)
    },
    searUser(xhsId) {
        let searchBtn = btnConfig.search.searchBtn
        let searchTabBtn = btnConfig.search.searchTabBtn
        setText(0, '')
        sleep(1000)
        setText(0, xhsId)
        App.randomSleep(2, 4)
        //点击搜索按钮
        let nowSearchBtn = searchBtn.default()
        if (!nowSearchBtn) {
            console.log('搜索按钮不存在，请检查并手动复原重新启动');
            getUserData.taskConfig.errorTask = '搜索按钮不存在'
            return
        }
        if (nowSearchBtn.bounds) {
            App.clickByBtn(nowSearchBtn, 3)
        } else {
            App.click(searchBtn.position.x, searchBtn.position.y, 3)
        }
        //切换到用户标签页
        let searchTab = searchTabBtn.default()
        if (!searchTab.length) {
            console.log('未查询到切换按钮，反馈异常')
            getUserData.taskConfig.errorTask = '未查询到切换按钮'
            return
        }
        searchTab.forEach(element => {
            let userBtn = element.findOne(text('用户'))
            let userBtn2 = element.findOne(text('账号'))
            if (userBtn) {
                App.clickByBtn(userBtn, 2)
            }
            if (userBtn2) {
                App.clickByBtn(userBtn2, 2)
            }
        });
        App.randomSleep(2, 4)
        let userImgBtn = btnConfig.search.searchUserImg.default()
        if (!userImgBtn.length) {
            console.log('未查询到切换按钮，反馈异常')
            getUserData.taskConfig.errorTask = '未查询到切换按钮'
            return
        }
        App.clickByBtn(userImgBtn[0], 3)
        getUserData.resolveNews()
    },
    resolveNews() {
        let messageList = getUserData.setting.deal_content ? getUserData.setting.deal_content.split('\n') : ''
        sendMessageBtn = btnConfig.user.sendMessageBtn.default() || btnConfig.user.sendMessageBtnFollow.default()
        if (!sendMessageBtn) {
            console.log('未找到发送私信按钮');
            getUserData.taskConfig.errorTask = '未找到发送私信按钮'
            return
        }
        App.clickByBtn(sendMessageBtn, 3)

        //执行回复
        let addBtn = btnConfig.message.messageSiXinFile.default()

        if (!addBtn) {
            console.log('回复任务：未找到私信文件按钮，请检查');
            getUserData.taskConfig.errorTask = '未找到私信文件按钮'
            return;
        }

        if (addBtn.bounds) {
            App.clickByBtn(addBtn, true)
        } else {
            App.clickByBtn(btnConfig.message.messageSiXinFile.position.x, btnConfig.message.messageSiXinFile.position.y, true)
        }

        // 保持内容文本为空
        setText('')
        sleep(2000)
        //处理发送文本
        if (messageList) {
            messageList.forEach((mess) => {
                setText(mess)
                sleep(2000)
                let sendMessageBtn = btnConfig.message.sendMessageBtn.default()
                if (!sendMessageBtn) {
                    console.log('回复任务：无法获取发送按钮，请检查')
                    setText('')
                } else {
                    if (!Xhs.isTest) {
                        if (sendMessageBtn.bounds) {
                            App.clickByBtn(sendMessageBtn, true)
                        } else {
                            App.clickByBtn(btnConfig.message.sendMessageBtn.position.x, btnConfig.message.sendMessageBtn.position.y, true)
                        }
                    } else {
                        console.log('测试阶段-可以发送评论');
                        sleep(2000)
                    }
                }
            })
        }
        //处理发送文件
        if (getUserData.saveFileList) {
            getUserData.sendfile(1)
        }

        getUserData.taskConfig.taskStatus = true
    },
    sendfile() {
        let fileBtn = btnConfig.message.messageSiXinFileImg.default()
        if(!fileBtn) {
            console.log('回复任务：无法获取文件按钮，请检查');
            return;
        }
        if (fileBtn.bounds) {
            App.clickByBtn(fileBtn, true)
        } else {
            App.clickByBtn(btnConfig.message.messageSiXinFileImg.position.x, btnConfig.message.messageSiXinFileImg.position.y, true)
        }
        // 等待文件选择界面加载完成
        let messageFileMenu = btnConfig.file.messageFileMenu.default()
        if (!messageFileMenu) {
            console.log('回复任务：无法加载文件选择界面');
            return
        }
        let fileItem = btnConfig.file.messageFileImgRadio.default()
        if (!fileItem.length) {
            console.log('回复任务：无法获取文件列表');
            return
        }
        //遍历对应资源，选中它
        fileItem.forEach((file, index) => {
            if (index < getUserData.saveFileList) {
                App.clickByBtn(file, 2)
            }
        })
        // if (getUserData.saveFileList > 1) {
        //     App.clickByBtn(fileItem[index], 2)
        // } else {
        //     App.clickByBtn(fileItem[0], 2)
        // }
        //发送
        let sendBtn = btnConfig.file.FileSend.default()
        if (!sendBtn) {
            console.log('回复任务：无法获取发送按钮');
            back()
            return;
        }
        console.log('文件下载总数', getUserData.saveFileList);
        if (!Xhs.isTest) {
            if (sendBtn.bounds) {
                App.clickByBtn(sendBtn, 3)
            } else {
                App.clickByBtn(btnConfig.file.FileSend.position.x, btnConfig.file.FileSend.position.y, 3)
            }
        } else {
            console.log('测试阶段-可以发送文件');
            sleep(2000)
            back()
            sleep(1000)
        }
    },
    resolveMiddle(seed) {
        console.log('FUNCTION: resolveMiddle');
        let resource = []
        if (seed.image) {
            //先下载的图片地址 位置1

            resource = seed.image.split(',')
        }
        if (seed.video) {
            //后下载的视频地址 位置0
            resource.push(seed.video)
        }
        sleep(2000)
        if (resource.length) {
            // if (!Xhs.isTest) {
                myUi.setTopText(Comman.getDate() + ': 回复任务：' + "资源准备中....")
            // }
            let num = 0
            resource.forEach((item, index) => {
                let urlName = item.split('/').slice(-1)[0]
                if (!urlName) {
                    console.log('回复任务：文件解析名称失败：' + item);
                    return
                }
                let filePath = Xhs.resourcePath + new Date().getTime() + '_' + urlName
                let fileStatus = files.createWithDirs(filePath)
                let response = http.get(item);
                if (response.statusCode == 200) {
                    let fileBytes = response.body.bytes();
                    files.writeBytes(filePath, fileBytes);
                    media.scanFile(filePath);
                    getUserData.saveFilePath.push(filePath)
                    num += 1
                    console.log('回复任务：文件下载完成：' + item + ' ---------NO：' + index);
                } else {
                    console.log('回复任务：文件解析名称失败' + response.statusCode);
                }
                sleep(500)
            })
            getUserData.saveFileList = num
        }
        sleep(1000)
    },
}
module.exports = getUserData